﻿using Bouyei.NetFactory;
using System;
using System.Net.Sockets.Kcp;
using System.Text;
using UnityEngine;

public class KcpTest2 : MonoBehaviour
{
    INetClientProvider clientProvider = null;
    int port = 16650;
    bool isConn = false;
    Kcp kcp = null;
    KcpCallback kcpCb = null;

    // Start is called before the first frame update
    void Start()
    {
        clientProvider = NetClientProvider.CreateProvider(4096, 4, NetProviderType.Udp);
        clientProvider.ReceiveOffsetHandler += OnReceivedSegmentHandler;
        ///119.23.39.55 127.0.0.1
        isConn = clientProvider.ConnectTo(port, "127.0.0.1");
        Debug.Log("isConn:" + isConn);
        const int conv = 123;
        kcpCb = new KcpCallback();
        kcpCb.OnOutput += OnOutput;
        kcp = new Kcp(conv, kcpCb);
        kcp.NoDelay(1, 10, 2, 1);//fast
        kcp.WndSize(64, 64);
        kcp.SetMtu(512); 
    }

    void OnOutput(Memory<byte> buffer)
    {
        Debug.Log("把kcp中需要发送的消息发送出去");
        clientProvider.Send(new SegmentOffset(buffer.ToArray())); 
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0) && isConn)
        {
            string msg = "客户端时间:" + GetTimeStamp();
            kcp.Send(Encoding.UTF8.GetBytes(msg));
            Debug.Log("把需要发送的消息放进kcp"); 
        }

        if (kcp != null)
        {
            kcp.Update(DateTime.UtcNow);
            //打印kcp接收到的消息
            int len;
            while ((len = kcp.PeekSize()) > 0)
            {
                var buffer = new byte[len];
                if (kcp.Recv(buffer) >= 0)
                {
                    Debug.Log("取出kcp收到的消息");
                    string msg = Encoding.UTF8.GetString(buffer);
                    Debug.Log(msg + " 客户端时间:" + GetTimeStamp());
                }
            }
        }
    }

    void OnReceivedSegmentHandler(SegmentToken session)
    {
        Debug.Log("接收消息放入kcp");
        byte[] buffer = new byte[session.Data.size];
        Buffer.BlockCopy(session.Data.buffer, session.Data.offset, buffer, 0, session.Data.size);
        kcp.Input(buffer);
    }

    private void OnApplicationQuit()
    {
        clientProvider.Dispose();
        kcp.Dispose();
    }

    public long GetTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds);
    }
}